import { Controller, Get, Post, Body, Patch, Param, Delete, ParseUUIDPipe, Query, Res, Header } from '@nestjs/common';
import { KnowledgeService } from './knowledge.service';
import { CreateKnowledgeDto, UpdateKnowledgeDto } from './dto';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { KnowledgeEntity } from './knowledge.entity';
import { ModuleSwaggerTags } from '~/constants/modules.constant';
import { Response } from 'express';
import { Public } from '../auth/decorators/public.decorator';

@ApiTags(ModuleSwaggerTags.KNOWLEDGE)
@ApiBearerAuth()
@Controller('cms/knowledge')
export class KnowledgeController {
  constructor(private readonly knowledgeService: KnowledgeService) {}

  @Post()
  @ApiOperation({ summary: '创建知识' })
  create(@Body() createKnowledgeDto: CreateKnowledgeDto): Promise<KnowledgeEntity> {
    return this.knowledgeService.create(createKnowledgeDto);
  }

  @Get()
  @ApiOperation({ summary: '获取所有知识列表' })
  findAll(): Promise<KnowledgeEntity[]> {
    return this.knowledgeService.findAll();
  }

  @Get('category/:categoryId')
  @ApiOperation({ summary: '根据分类ID获取知识列表' })
  findByCategoryId(@Param('categoryId') categoryId: number): Promise<KnowledgeEntity[]> {
    return this.knowledgeService.findByCategoryId(categoryId);
  }

	@Public()
  @Get('category/html/:categoryId')
  @ApiOperation({ summary: '根据分类ID获取知识列表(HTML格式)' })
	@Header('Content-Type', 'text/html')
  async findByCategoryIdAsHtml(
    @Param('categoryId') categoryId: number,
		@Res() res: Response
  ): Promise<void> {
    let content = await this.knowledgeService.findByCategoryIdAsHtml(categoryId);
		// 使用正则将pre标签替换成p标签
		content = content.replace(/<pre>/g, '<p>').replace(/<\/pre>/g, '</p>');
    res.header('Content-Type', 'text/html').send(content);
  }

  @Get(':id')
  @ApiOperation({ summary: '根据ID获取知识详情' })
  findOne(@Param('id') id: number): Promise<KnowledgeEntity> {
    return this.knowledgeService.findOne(id);
  }

  @Patch(':id')
  @ApiOperation({ summary: '更新知识' })
  update(
    @Param('id') id: number,
    @Body() updateKnowledgeDto: UpdateKnowledgeDto,
  ): Promise<KnowledgeEntity> {
    return this.knowledgeService.update(id, updateKnowledgeDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除知识' })
  remove(@Param('id') id: number): Promise<void> {
    return this.knowledgeService.remove(id);
  }
}
